package com.tgl.vegetables.plug.meitu;

import android.accessibilityservice.AccessibilityService;
import android.graphics.Rect;
import android.os.Message;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;

import androidx.annotation.NonNull;

import com.tgl.vegetables.plug.service.BaseAccessibilityService;

public class MeituPreferredAccessibilityService extends BaseAccessibilityService {

    private static final String TAG = "MeituPreferredAccessibilityService";

    public MeituPreferredAccessibilityService() {
        super();
        mHandler.removeMessages(MSG_CLICK_EVENT);
    }

    @Override
    public void onAccessibilityEvent(AccessibilityService context, AccessibilityEvent accessibilityEvent) {
        super.onAccessibilityEvent(context, accessibilityEvent);
        Log.e(TAG, "accessibilityEvent = " + accessibilityEvent.toString());
        int type = accessibilityEvent.getEventType();
        String className = accessibilityEvent.getClassName().toString();
        if (type == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            switch (className) {
                case "com.meituan.mmp.lib.mp.MPActivity0":
                    mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
                    break;
                default:
                    break;
            }
        }
    }

    private void goPay() {
        AccessibilityNodeInfo root = mAccessibilityService.getRootInActiveWindow();
        AccessibilityNodeInfo nodeInfo = findAccessibilityNodeInfo(root, "购物车", 0);
        if(nodeInfo == null || !nodeInfo.isSelected()){
            return;
        }
        Rect rect = new Rect();
        nodeInfo.getParent().getBoundsInScreen(rect);
        autoClickPoint(rect.right + 40, rect.top - 40);
    }

    @Override
    protected long getDuration() {
        return 30;
    }

    @Override
    public boolean handleMessage(@NonNull Message message) {
        switch (message.what) {
            case MSG_CLICK_EVENT:
                goPay();
                mHandler.sendEmptyMessageDelayed(MSG_CLICK_EVENT, getDuration());
                break;
        }
        return false;
    }
}
